<template>
  <div class="flex h-full items-stretch">
    <div class="flex-1 flex flex-col p-4" :class="plain ? '' : 'shadow-md'">
      <!-- <el-input v-model="" placeholder="搜索员工"></el-input> -->
      <div class="mb-2">
        <span v-for="(item, index) in treeList" :key="item.pid" v-show="index <= active">
          <span v-show="index !== 0">&nbsp;/</span>
          <span class="cursor-pointer hover:text-action" @click="active = index">{{ item.name }}</span>
        </span>
      </div>
      <el-checkbox v-if="multiple" v-model="checkedAll" :disabled="checkedAllDisabled">全选</el-checkbox>
      <div class="flex-1 overflow-y-auto">
        <div class="flex justify-between" v-for="item in activeList.departmentList" :key="item.department_id">
          <div class="flex items-center text-sm cursor-pointer text-gray-700 hover:text-action"
            @click="isDep ? onCheck(item) : nodeDataLoad(item)">
            <el-checkbox v-if="isDep && multiple" class="!mr-2" :modelValue="isChecked(item)" />
            <el-icons class="mr-1" size="1rem" name="Menu" />
            <div class="flex-1">{{ item.name }}</div>
          </div>
          <el-button type="primary" text @click="nodeDataLoad(item)">下级</el-button>
        </div>

        <div v-if="!isDep" class="flex" v-for="item in activeList.userList" :key="item.user_id">
          <el-checkbox :modelValue="isChecked(item)" @update:modelValue="onCheck(item)">
            <div class="flex items-center text-gray-700 hover:text-action">
              <el-icons class="mr-1" size="1rem" name="Avatar" /> {{ item.name }}
            </div>
          </el-checkbox>
        </div>

        <EmptyImg class="!h-full" v-if="!activeList.departmentList.length && !activeList.userList.length" />
      </div>
    </div>
    <div v-if="multiple && !plain" class="flex-1 ml-3 flex flex-col p-4" :class="plain ? '' : 'shadow-md'">
      <div class="mb-2">{{ isDep ? '已选部门' : '已选员工' }}</div>
      <div class="flex-1 overflow-y-auto">
        <div class="flex items-center text-sm text-gray-700 h-8" v-for="(item, index) in checkedList"
          :key="isDep ? item.department_id : item.user_id">
          <el-icons class="mr-1" size="1rem" :name="isDep ? 'Menu' : 'Avatar'" />
          <div class="flex-1">{{ item.name }}</div>
          <el-icons class="cursor-pointer ml-1" size="1rem" name="CircleClose" @click="onDelete(index)" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { departmentServer, userServer } from '@/api'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const props = defineProps({
  isDep: Boolean, // 是否为部门选择器
  defaultCheckedList: {
    type: Array,
    default: () => []
  }, // 默认选中列表
  rootNode: Object, // 根节点
  multiple: Boolean, // 是否多选
  plain: Boolean, // 是否为扁平化样式
})
const emit = defineEmits(['change', 'update:visible']);

const active = ref(0)
const treeList = ref([
  {
    name: '组织架构',
    department_id: 'root',
    departmentList: [{
      name: props.rootNode?.name || userStore.departmentName,
      department_id: props.rootNode?.department_id || userStore.departmentId
    }],
    userList: []
  }
]) // 树形列表
const activeList = computed(() => {
  return treeList.value[active.value]
})

const checkedList = ref([...props.defaultCheckedList]) // 选中列表
defineExpose({
  setCheckedList: (list) => {
    checkedList.value = list;
  },
  getCheckedList: () => {
    return checkedList.value;
  }
})

const checkedAll = computed({
  get() {
    const idKey = props.isDep ? 'department_id' : 'user_id';
    const list = (props.isDep ? activeList.value?.departmentList : activeList.value?.userList) || [];
    const map = new Set();
    checkedList.value.forEach(v => {
      map.add(v[idKey]);
    })
    return list.every(v => map.has(v[idKey]))
  },
  set(val) {
    const idKey = props.isDep ? 'department_id' : 'user_id';
    const list = (props.isDep ? activeList.value?.departmentList : activeList.value?.userList) || [];
    if (val) {
      const map = new Set();
      checkedList.value.forEach(v => {
        map.add(v[idKey]);
      })
      list.forEach(v => {
        if (!map.has(v[idKey])) {
          checkedList.value.push(v);
        }
      })
    } else {
      const map = new Set();
      list.forEach(v => {
        map.add(v[idKey]);
      })
      checkedList.value = checkedList.value.filter(v => !map.has(v[idKey]));
    }
  }
})
const checkedAllDisabled = computed(() => {
  const list = (props.isDep ? activeList.value?.departmentList : activeList.value?.userList) || [];
  return list.length === 0;
})


const onDelete = (i) => { //  删除已选择的
  checkedList.value.splice(i, 1);
}

const nodeDataLoad = async ({ name, department_id }) => { // 加载pid下的 数据
  active.value++;
  const node = {
    name,
    departmentId: department_id,
    departmentList: [],
    userList: [],
  }
  treeList.value[active.value] = node;
  treeList.value.length = active.value + 1;

  const res = await Promise.all([
    departmentServer.get({ pid: node.departmentId }),
    props.isDep ? Promise.resolve() : userServer.get({ department_id: node.departmentId, size: 99 })
  ])

  const current = treeList.value[active.value];
  current.departmentList = res[0]?.data || [];
  current.userList = res[1]?.data?.data_list || [];
}
nodeDataLoad({
  name: props.rootNode?.name || userStore.departmentName,
  department_id: props.rootNode?.department_id || userStore.departmentId
}); // 初始化加载根节点数据

const isChecked = (item) => { // 是否被选中
  const idKey = props.isDep ? 'department_id' : 'user_id';
  return checkedList.value.some(v => v[idKey] === item[idKey]);
}
const onCheck = (item) => { // 选中
  const idKey = props.isDep ? 'department_id' : 'user_id';
  const index = checkedList.value.findIndex(v => v[idKey] === item[idKey]);
  if (index > -1) {
    if (!props.multiple) return; // 如果是单选，不支持取消
    checkedList.value.splice(index, 1);
  } else {
    if (props.multiple) {
      checkedList.value.push(item);
    } else {
      checkedList.value = [item];
    }
  }
  emit('change', checkedList.value)
}
</script>